﻿using System;
using System.Linq;
using System.Web.Mvc;
using Pyramid.Bll;
using Pyramid.Models;

namespace Pyramid.Controllers
{
	public class PayVerifyController : PaymentBaseController
	{
		private readonly PaymentHelper _helper = new PaymentHelper();

		public ActionResult List(PaymentQueryModel model)
		{
			return View(PrepareForPaymentListView(model, true));
		}

		public ActionResult Verify(int payRecordId)
		{
			var record = _helper.Single(payRecordId);
			if (record.StatusEnum == PayeeRecordStatus.Verified)
			{
				var verifyModel = Db.PayeeVerifies.Single(x => x.Id == record.VerifyId);
				return View("VerifyReadOnly", verifyModel);
			}

			var model = new PayeeVerify {VerifyTime = DateTime.Now, VerifyUserId = User.UserId, PayeeRecordId = payRecordId};
			return View("VerifyForm", model);
		}

		[HttpPost]
		public ActionResult Verify(PayeeVerify model)
		{
			if (model.Id > 0)
			{
				return JError("数据被篡改，不能提交！");
			}

			//添加审核确认信息
			model.VerifyTime = DateTime.Now;
			model.VerifyUserId = User.UserId;
			Db.PayeeVerifies.Add(model);
			Db.SaveChanges();

			//更新付款信息状态
			var record = Db.PayeeRecords.Single(x => x.Id == model.PayeeRecordId);
			record.Status = (int) PayeeRecordStatus.Verified;
			record.VerifyId = model.Id;
			Db.SaveChanges();

			//顾客充值，确认后
			if (record.PayerTypeEnum == PayerTypes.Customer)
			{
				var cc = Db.CustomerCapitals.SingleOrDefault(x => x.CustomerId == record.PayerId);
				if (cc == null)
				{
					cc = new CustomerCapital {CustomerId = record.PayerId, Balance = record.Amount, ConsumeTotal = 0, RechargeTotal = 0};
					Db.CustomerCapitals.Add(cc);
				}
				else
				{
					cc.Balance += record.Amount;
					cc.RechargeTotal += record.Amount;
				}
				Db.SaveChanges();
			}

			return JSuccess("操作成功！", "tab_fin_payverify");
		}
	}
}